package ntu.p2p.dht.messaging;

import java.io.IOException;

import ntu.p2p.dht.DHTContentKey;
import ntu.p2p.dht.test.Key;
import ntu.p2p.past.messaging.ObjectDifference;
import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;

public class DHTUpdateObjectMessage implements ObjectDifference {

	public static final short TYPE = 2;
	
	private DHTContentKey key;
	private DHTObjectDifference dhtObjectDifference;
	
	public DHTUpdateObjectMessage(DHTContentKey key, DHTObjectDifference difference) {
		this.key = key;
		this.dhtObjectDifference = difference;
	}
	
	protected DHTUpdateObjectMessage(InputBuffer buf, 
			DHTDifferenceDeserializer deserializer, Endpoint endpoint) throws IOException {
		this.key = Key.build(buf, endpoint);
		this.dhtObjectDifference = deserializer.deserialize(buf);
	}
	
	public DHTContentKey getKey() {
		return key;
	}
	
	public DHTObjectDifference getDifference() {
		return dhtObjectDifference;
	}
	
	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		buf.writeShort(TYPE);
		this.key.serialize(buf);
		this.dhtObjectDifference.serialize(buf);
	}
	
	public static DHTUpdateObjectMessage build(InputBuffer buf, 
			DHTDifferenceDeserializer deserializer, Endpoint endpoint) {
		try {
			return new DHTUpdateObjectMessage(buf, deserializer, endpoint);
		} catch (IOException e) {
			return null;
		}
	}
}
